package org.jeecg.modules.demo.cashier;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeFastpayRefundQueryModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.IpUtils;
import org.jeecg.modules.demo.mall.api.MallHelloApi;
import org.jeecg.modules.demo.mall.entity.YxUser;
import org.jeecg.modules.demo.util.Allinpay;
import org.jeecg.modules.demo.weixin.dto.PayDto;
import org.jeecg.modules.demo.weixin.dto.RefundDto;
import org.jeecg.modules.demo.weixin.entity.*;
import org.jeecg.modules.demo.weixin.merchantpay.service.IMerchantPayService;
import org.jeecg.modules.demo.weixin.payorder.service.IPayOrderService;
import org.jeecg.modules.demo.weixin.refundrecord.service.IRefundRecordService;
import org.jeecg.modules.demo.weixin.smtoncecarddeduction.service.ISmtOnceCardDeductionService;
import org.jeecg.modules.demo.weixin.smtoncecardusers.service.ISmtOnceCardUsersService;
import org.jeecg.modules.demo.weixin.smtstoreduserpoint.service.ISmtStoredUserPointService;
import org.jeecg.modules.demo.weixin.smtyuyuelist.service.ISmtYuyueListService;
import org.jeecg.modules.demo.weixin.smtyuyueuser.service.ISmtYuyueUserService;
import org.jeecg.modules.demo.weixin.util.MD5Util;
import org.jeecg.modules.demo.weixin.util.ZfbConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 收银台 扫码支付接口
 * @Author: jeecg-boot
 * @Date: 2023-10-23
 * @Version: V1.0
 */
@RestController
@RequestMapping("/weixin/pay")
@Slf4j
public class CashierPayController {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IRefundRecordService recordService;

    @Autowired
    private ISmtYuyueListService yuyueListService;
    @Autowired
    private ISmtYuyueUserService smtYuyueUserService;

    @Autowired
    private MallHelloApi mallHelloApi;


    @Autowired
    private ISmtStoredUserPointService smtStoredUserPointService;

    @Autowired
    private ISmtOnceCardDeductionService smtOnceCardDeductionService;

    @Autowired
    private ISmtOnceCardUsersService smtOnceCardUsersService;
    @Autowired
    private IMerchantPayService merchantPayService;

    /**
     * 扫码支付
     *
     * @param payDto
     * @return
     */
    @SneakyThrows
    @PostMapping("/payOrder1")
    public Result<?> payOrder1(@RequestBody PayDto payDto, HttpServletRequest request) {
        //获取当前ip
        payDto.setSpbillCreateIp(IpUtils.getIpAddr(request));
        if (payDto.getPayPrice() == null || payDto.getTotalPrice() == null || payDto.getCashPay() == null || payDto.getBalancePay() == null || payDto.getActualPrice() == null) {
            return Result.error("传参不正确 金额为null传0");
        }
        //判断金额是否为负数
        if (payDto.getPayPrice().compareTo(BigDecimal.ZERO) < 0 || payDto.getTotalPrice().compareTo(BigDecimal.ZERO) < 0 || payDto.getCashPay().compareTo(BigDecimal.ZERO) < 0 || payDto.getBalancePay().compareTo(BigDecimal.ZERO) < 0 || payDto.getActualPrice().compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("含有金额为负数 请检查金额");
        }
        //总金额
        BigDecimal zong = payDto.getCashPay().add(payDto.getBalancePay()).add(payDto.getPayPrice());

        if (payDto.getIsCoupon() != null) {
            if (payDto.getIsCoupon().equals(0)) {
                if (zong.add(payDto.getActivityPrice()).compareTo(payDto.getTotalPrice()) < 0) {
                    return Result.error("金额核算不正确");
                }
            } else {
                if (zong.compareTo(payDto.getTotalPrice()) < 0) {
                    return Result.error("金额核算不正确");
                }
            }
        }
        //前端判断后期不一定优惠金额是不是
        if (payDto.getCouponId() == null && payDto.getActivityPrice() != null && (!payDto.getActivityPrice().equals(BigDecimal.ZERO))) {
            payDto.setIsCoupon(1);
        }
        //以上是校验     后期可以 后期可以封装到  一个方法里面
        if (payDto.getOrderType() == 3 && StringUtils.isNotBlank(payDto.getYuYueId())) {
            //查询选择的排期是否人数已满
            SmtYuyueList yuyueList = yuyueListService.getById(payDto.getYuYueId());
            if (yuyueList != null) {
                if (payDto.getCount() > (yuyueList.getCount() - yuyueList.getNum())) {
                    return Result.error(606, "当前排期人数已满，请选择其他排期！");
                }
                if (yuyueList.getStartTime().compareTo(new Date()) < 1) {
                    return Result.error(606, "游戏已经开始无法加入");
                }
            }

        }


        //生成支付订单
        PayOrder payOrder = new PayOrder();
        //生成订单编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNo = MD5Util.encryptMd5(simpleDateFormat.format(new Date()) + RandomUtil.randomNumbers(10));
        //保存订单
        BeanUtils.copyProperties(payDto, payOrder);
        payOrder.setUserId(payDto.getUid());
        payOrder.setTrkName(getTrkName(payDto));
        payOrder.setOrderType(payDto.getOrderType() == 1 ? 1 : payDto.getOrderType() == 2 ? 2 : payDto.getOrderType() == 3 ? 3 : payDto.getOrderType());
        payOrder.setPayPrice(payDto.getPayPrice());
        payOrder.setOrderNo(orderNo);
        payOrder.setActualPrice(payDto.getActualPrice());
        payOrder.setMerchantId(payDto.getMerId());
        payOrder.setYuyueId(payDto.getYuYueId() == null ? null : payDto.getYuYueId());
        payDto.setOrderCouponNo(payOrder.getOrderNo());
        //根据不同的订单类型创建订单
        Result<?> orderByOrderType = payOrderService.saveOrderByOrderType(payDto, payOrder);
        if (orderByOrderType.getCode() == 200) {
            //添加积分  充值不赠送积分以及成长值
            if (payDto.getUid() != null && payDto.getOrderType() != 1) {
                if (payDto.getIntegral() != null) {
                    YxUser yxUser = new YxUser();
                    yxUser.setUid(payDto.getUid());
                    yxUser.setIntegral(payDto.getIntegral());
                    mallHelloApi.addIntegral(yxUser);
                }
                //添加成长值
                mallHelloApi.growthValueCalculation(payDto);
            }
            return Result.OK(orderByOrderType.getMessage());
        } else if (orderByOrderType.getCode() == 608) {
            payOrder.setPayStatus("1");
            payOrderService.save(payOrder);
        } else {
            return Result.error(606, orderByOrderType.getMessage());
        }

        //如果是充次订单则走此逻辑
        if (payDto.getOrderType() == 2) {
            payOrderService.card(payDto, payOrder.getId());
        }
        //如果是商家商品订单则走此逻辑
        if (payDto.getOrderType() == 6 || payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
            payOrderService.merchantShop(payDto, payOrder.getId());
        }
        //优惠券
        if (payDto.getIsCoupon() != null && payDto.getIsCoupon().equals(0)) {
            mallHelloApi.editCouponUser(payDto.getCouponId(), payDto.getOrderCouponNo());
        }

//        Map<String, String> result = null;
        //调用商家微信付款码支付
        //微信支付
//        result = payOrderService.servicePayOrder(payDto, payOrder.getId());
        //通商云支付
        JSONObject jsonObject = Allinpay.agentCollectApply(payDto, String.valueOf(payOrder.getId()));
//        if (result.get("result_code").equals("SUCCESS") && result.get("return_code").equals("SUCCESS") && result.get("trade_type").equals("MICROPAY")) {
        if (jsonObject != null && jsonObject.getString("payStatus").equals("success")) {
            //更新订单状态
            payOrder.setPayTime(new Date());
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null && payDto.getYuYueId() == null) {
                payOrder.setPayStatus("5");
            } else {
                payOrder.setPayStatus("2");
            }
            payOrder.setTransactionId(jsonObject.getString("orderNo"));
            payOrder.setPayType(jsonObject.getString("payInterfacetrxcode"));
            if (payOrder.getBalancePay().compareTo(BigDecimal.ZERO) > 0) {
                payOrder.setPayType("WeChat&ValueCard");
            } else if (payOrder.getCashPay().compareTo(BigDecimal.ZERO) > 0) {
                payOrder.setPayType("WeChat&cash");
            } else {
                payOrder.setPayType("WeChat");
            }
            payOrderService.updateById(payOrder);

            //用户余额处理
            Result<?> balance = payOrderService.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            //添加积分 充值不赠送积分以及成长值
            if (payDto.getUid() != null && payDto.getOrderType() != 1) {
                if (payDto.getIntegral() != null) {
                    YxUser yxUser = new YxUser();
                    yxUser.setUid(payDto.getUid());
                    yxUser.setIntegral(payDto.getIntegral());
                    mallHelloApi.addIntegral(yxUser);
                }
                //添加成长值
                mallHelloApi.growthValueCalculation(payDto);
            }
            return Result.OK("支付成功！");
        }

        //支付返回需要输入支付密码时走此逻辑
        if (jsonObject != null && jsonObject.getString("payStatus").equals("pending")) {
            Thread.sleep(20000);
//            Result<?> orderStatus = null;
            //请求查询订单接口
            JSONObject orderStatus = Allinpay.getOrderStatus(jsonObject.getString("orderNo"), jsonObject.getString("bizOrderNo"));
//            orderStatus = payOrderService.queryOrder(payDto, payOrder.getId());
//            if (orderStatus.getCode() != 200) {
            if (orderStatus == null) {
                return Result.error(606, "支付状态查询失败");
            }
            if (orderStatus != null && orderStatus.getInteger("orderStatus") == 1) {
                payOrder.setPayStatus("1");
                payOrderService.updateById(payOrder);
            }

            //添加积分 充值不赠送积分以及成长值
            if (orderStatus != null && orderStatus.getInteger("orderStatus") == 4) {
                if (payDto.getUid() != null && payDto.getOrderType() != 1) {
                    if (payDto.getIntegral() != null) {
                        YxUser yxUser = new YxUser();
                        yxUser.setUid(payDto.getUid());
                        yxUser.setIntegral(payDto.getIntegral());
                        mallHelloApi.addIntegral(yxUser);
                    }
                    //添加成长值
                    mallHelloApi.growthValueCalculation(payDto);
                }
                return Result.OK("支付成功");
            } else {
                return Result.error(606, orderStatus.getString("errorMessage"));
            }
        }
        return Result.error(606, "支付失败");
    }


    /**
     * 申请退款
     *
     * @param refundDto
     * @return
     */
    @SneakyThrows
    @PostMapping("/refund1")
    public Result<?> refund1(@RequestBody RefundDto refundDto) {

        //判断当前订单是否已经退款
        QueryWrapper<RefundRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", refundDto.getOutTradeNo());
        RefundRecord record = recordService.getOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(record) && record.getRefundStatus() == 2) {
            return Result.error(606, "当前订单已退款!");
        }

        RefundRecord refundRecord = new RefundRecord();
        PayOrder payOrder = payOrderService.getById(refundDto.getOutTradeNo());
        if (payOrder == null) {
            return Result.error(606, "订单不存在");
        }
        if (!payOrder.getPayStatus().equals("2")) {
            return Result.error(606, "当前订单未支付完成或者已经退款！");
        }
        //判断排期是否过期过期后不进行退款
        if (payOrder.getOrderType() == 3) {
            LambdaQueryWrapper<SmtYuyueUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SmtYuyueUser::getLinkPayOrderNo, payOrder.getOrderNo());
            List<SmtYuyueUser> smtYuyueUsers = smtYuyueUserService.list(wrapper);
            if (!CollectionUtils.isEmpty(smtYuyueUsers)) {
                SmtYuyueList yuyueListById = yuyueListService.getById(smtYuyueUsers.get(0).getId());
                if (yuyueListById != null) {
                    if (yuyueListById.getStartTime().compareTo(new Date()) < 0) {
                        return Result.error(606, "订单已经过期，不可退款");
                    }
                }
            }

        }

        //扣次管理
        if (payOrder.getOrderType() == 7) {
            LambdaQueryWrapper<SmtOnceCardDeduction> smtOnceCardDeductionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            smtOnceCardDeductionLambdaQueryWrapper.eq(SmtOnceCardDeduction::getOrderNo, payOrder.getOrderNo());
            SmtOnceCardDeduction one = smtOnceCardDeductionService.getOne(smtOnceCardDeductionLambdaQueryWrapper);
            if (one == null) {
                return Result.error(606, "扣次记录不存在");
            }
            SmtOnceCardUsers smtOnceCardUsers = smtOnceCardUsersService.getById(one.getCardId());
            if (smtOnceCardUsers == null) {
                return Result.error("次卡信息不存在了");
            }
            smtOnceCardUsers.setCardRest(smtOnceCardUsers.getCardRest() + one.getOrderRest());
            smtOnceCardUsersService.updateById(smtOnceCardUsers);
            BeanUtils.copyProperties(refundDto, refundRecord);
            refundRecord.setTotalFee(refundDto.getTotalPrice());
            refundRecord.setRefundFee(refundDto.getRefundPrice());

//                refundRecord.setRefundId(stringStringMap.get("refund_id"));
//                refundRecord.setMchId(stringStringMap.get("mch_id"));
//                refundRecord.setSubMchId(stringStringMap.get("sub_mch_id"));
            refundRecord.setRefundStatus(2);
            recordService.save(refundRecord);
//            payOrder.setRefundId(refundRecord.getRefundId());
//            payOrder.setRefundTime(new Date());
//            payOrder.setPayStatus("3");
//            payOrder.setRefundFee(refundRecord.getRefundFee());
//            payOrderService.updateById(payOrder);
            Result<?> result = payOrderService.updateOrder(refundRecord);
            if (result.getCode() != 200) {
                return Result.error(606, result.getMessage());
            }
            return Result.OK("扣次退款成功！");

        }

        Result<?> refundByOrderType = recordService.refundByOrderType(refundDto, payOrder, refundRecord);
        if (refundByOrderType.getCode() == 200) {
            //退还积分充值不赠送积分以及成长值
            if (payOrder.getUserId() != null && payOrder.getOrderType() != 1) {
                if (payOrder.getIntegral() != null) {
                    YxUser yxUser = new YxUser();
                    yxUser.setUid(payOrder.getUserId());
                    yxUser.setIntegral(payOrder.getIntegral());
                    mallHelloApi.subIntegral(yxUser);
                }
                //扣除成长值
                mallHelloApi.subgrowthValues(payOrder.getUserId(), payOrder.getOrderNo());
            }
            return Result.OK(refundByOrderType.getMessage());
        } else if (refundByOrderType.getCode() == 608) {
            if (payOrder.getOrderType() == 1) {
                BigDecimal bigDecimal = smtStoredUserPointService.subPoint(payOrder.getTotalPrice(), payOrder.getGivePrice(), payOrder.getUserId(), String.valueOf(refundDto.getMerId()), payOrder.getOrderNo());
                if (bigDecimal == null) {
                    return Result.error(606, "用户卡点状态不支持退款");
                }
                refundDto.setRefundPrice(bigDecimal);
            }
            //调用退款接口
            //微信退款
//            Map<String, String> stringStringMap = recordService.refund(refundDto, refundDto.getOutTradeNo());
            //调用通商云退款
            JSONObject refund = Allinpay.refund(String.valueOf(payOrder.getId()), payOrder.getTransactionId(), refundDto.getPayPrice());
//            if (stringStringMap.get("return_code").equals("SUCCESS") && stringStringMap.get("result_code").equals("SUCCESS")) {
            if (refund != null && refund.getString("payStatus").equals("success")) {
                //生成退款记录
                BeanUtils.copyProperties(refundDto, refundRecord);
                refundRecord.setTotalFee(refundDto.getTotalPrice());
                refundRecord.setRefundFee(refundDto.getRefundPrice());

                refundRecord.setRefundId(refund.getString("bizOrderNo"));
//                refundRecord.setRefundId(stringStringMap.get("refund_id"));
//                refundRecord.setMchId(stringStringMap.get("mch_id"));
//                refundRecord.setSubMchId(stringStringMap.get("sub_mch_id"));
                refundRecord.setRefundStatus(2);
                recordService.save(refundRecord);

                //处理订单逻辑
                Result<?> result = payOrderService.updateOrder(refundRecord);
                if (result.getCode() != 200) {
                    return Result.error(606, result.getMessage());
                }
                //退还积分  充值不赠送积分以及成长值
                if (payOrder.getUserId() != null && payOrder.getOrderType() != 1) {
                    if (payOrder.getIntegral() != null) {
                        YxUser yxUser = new YxUser();
                        yxUser.setUid(payOrder.getUserId());
                        yxUser.setIntegral(payOrder.getIntegral());
                        mallHelloApi.subIntegral(yxUser);
                    }
                    //扣除成长值
                    mallHelloApi.subgrowthValues(payOrder.getUserId(), payOrder.getOrderNo());
                }
                return Result.OK("退款成功！", refund);
            }
//            return Result.error(606, stringStringMap.get("err_code_des"));
            return Result.error(606, "退款失败！");
        } else {
            return Result.error(606, refundByOrderType.getMessage());
        }
    }

    /**
     * 加入场次的用户可以被踢出去
     */
    @SneakyThrows
    @GetMapping("/refundCard")
    public Result<?> refundCard(@RequestParam String orderNo) {
        LambdaQueryWrapper<PayOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PayOrder::getOrderNo, orderNo);
        PayOrder payOrder = payOrderService.getOne(queryWrapper);
        if (payOrder == null) {
            return Result.error("该订单不存在！");
        }
        if (payOrder.getOrderType() == 7) {
            return Result.error("通过次卡支付，无法进行退款");
        }
        RefundDto refundDto = new RefundDto();
        refundDto.setCashPay(payOrder.getCashPay());
        refundDto.setOutTradeNo(String.valueOf(payOrder.getId()));
        refundDto.setRefundPrice(payOrder.getActualPrice());
        refundDto.setPayPrice(payOrder.getPayPrice());
        refundDto.setBalancePay(payOrder.getBalancePay());
        refundDto.setTotalPrice(payOrder.getTotalPrice());
        refundDto.setTransactionId(payOrder.getTransactionId());
        refundDto.setMerId(Integer.valueOf(payOrder.getMerchantId()));
        return refund(refundDto);
    }


    /**
     * 待支付 订单支付
     *
     * @param payDto
     * @return
     */
    @SneakyThrows
    @PostMapping("/toBePaid")
    public Result<?> toBePaid(@RequestBody PayDto payDto, HttpServletRequest request) {
        //获取当前ip
        payDto.setSpbillCreateIp(IpUtils.getIpAddr(request));
        PayOrder payOrder = payOrderService.getById(payDto.getOutTradeNo());
        if (!payOrder.getPayStatus().equals("1")) {
            return Result.error("该订单状态不是待支付状态！");
        }
        if (payDto.getOrderType() == 3 && StringUtils.isNotBlank(payDto.getYuYueId())) {
            //查询选择的排期是否人数已满
            SmtYuyueList yuyueList = yuyueListService.getById(payDto.getYuYueId());
            if (payDto.getCount() > (yuyueList.getCount() - yuyueList.getNum())) {
                return Result.error(606, "当前排期人数已满，请选择其他排期！");
            }
            Date date = new Date();
            if (date.compareTo(yuyueList.getEndTime()) > 0) {
                return Result.error(606, "排期状态已过期");
            }
        }

        Result<?> orderByOrderType = payOrderService.orderByOrderType(payDto, payOrder);
        if (orderByOrderType.getCode() == 200) {
            //添加积分  充值不赠送积分以及成长值
            if (payDto.getUid() != null && payDto.getOrderType() != 1) {
                if (payDto.getIntegral() != null) {
                    YxUser yxUser = new YxUser();
                    yxUser.setUid(payDto.getUid());
                    yxUser.setIntegral(payDto.getIntegral());
                    mallHelloApi.addIntegral(yxUser);
                }
                //添加成长值
                mallHelloApi.growthValueCalculation(payDto);
            }
            return Result.OK(orderByOrderType.getMessage());
        } else if (orderByOrderType.getCode() == 608) {
            payOrder.setPayStatus("1");
            payOrderService.save(payOrder);
        } else {
            return Result.error(606, orderByOrderType.getMessage());
        }

        JSONObject jsonObject = Allinpay.consumeApply(payDto, String.valueOf(payOrder.getId()));
//        if (result.get("result_code").equals("SUCCESS") && result.get("return_code").equals("SUCCESS") && result.get("trade_type").equals("MICROPAY")) {
        if (jsonObject != null && jsonObject.getString("payStatus").equals("success")) {
            //更新订单状态
            payOrder.setPayTime(new Date());
            if (payDto.getOrderType() == 3 && payDto.getShopRecordList() != null && payDto.getYuYueId() == null) {
                payOrder.setPayStatus("5");
            } else {
                payOrder.setPayStatus("2");
            }
            payOrder.setTransactionId(jsonObject.getString("orderNo"));
            payOrder.setPayType(jsonObject.getString("payInterfacetrxcode"));
            if (payOrder.getBalancePay().compareTo(BigDecimal.ZERO) > 0) {
                payOrder.setPayType("WeChat&ValueCard");
            } else if (payOrder.getCashPay().compareTo(BigDecimal.ZERO) > 0) {
                payOrder.setPayType("WeChat&cash");
            } else {
                payOrder.setPayType("WeChat");
            }
            payOrderService.updateById(payOrder);

            //用户余额处理
            Result<?> balance = payOrderService.balance(payDto);
            if (balance.getCode() != 200) {
                return Result.error(606, balance.getMessage());
            }
            //添加积分 充值不赠送积分以及成长值
            if (payDto.getUid() != null && payDto.getOrderType() != 1) {
                if (payDto.getIntegral() != null) {
                    YxUser yxUser = new YxUser();
                    yxUser.setUid(payDto.getUid());
                    yxUser.setIntegral(payDto.getIntegral());
                    mallHelloApi.addIntegral(yxUser);
                }
                //添加成长值
                mallHelloApi.growthValueCalculation(payDto);
            }
            return Result.OK("支付成功！");
        }

        //支付返回需要输入支付密码时走此逻辑
        if (jsonObject != null && jsonObject.getString("payStatus").equals("pending")) {
            Thread.sleep(20000);
//            Result<?> orderStatus = null;
            //请求查询订单接口
            JSONObject orderStatus = Allinpay.getOrderStatus(jsonObject.getString("orderNo"), jsonObject.getString("bizOrderNo"));
//            orderStatus = payOrderService.queryOrder(payDto, payOrder.getId());
//            if (orderStatus.getCode() != 200) {
            if (orderStatus == null) {
                return Result.error(606, "支付状态查询失败");
            }
            if (orderStatus != null && orderStatus.getInteger("orderStatus") == 1) {
                payOrder.setPayStatus("1");
                payOrderService.updateById(payOrder);
            }

            //添加积分 充值不赠送积分以及成长值
            if (orderStatus != null && orderStatus.getInteger("orderStatus") == 4) {
                if (payDto.getUid() != null && payDto.getOrderType() != 1) {
                    if (payDto.getIntegral() != null) {
                        YxUser yxUser = new YxUser();
                        yxUser.setUid(payDto.getUid());
                        yxUser.setIntegral(payDto.getIntegral());
                        mallHelloApi.addIntegral(yxUser);
                    }
                    //添加成长值
                    mallHelloApi.growthValueCalculation(payDto);
                }
                return Result.OK("支付成功");
            } else {
                return Result.error(606, orderStatus.getString("errorMessage"));
            }
        }
        return Result.error(606, "支付失败");
    }


    /**
     * 待支付   24 小时订单自动取消接口
     *
     * @param orderId
     * @return
     */
    @SneakyThrows
    @GetMapping("/cancellation")
    public Result<?> cancellation(@RequestParam Integer orderId) {
        PayOrder payOrder = payOrderService.getById(orderId);
        if (payOrder == null) {
            return Result.error("订单不存在!");
        }
//获取当前时间
        Date date = new Date();
//获取订单24小时后的订单
        Date time = payOrder.getCreateTime();
        time.setDate(payOrder.getCreateTime().getDate() + 1);
        if (date.after(time)) {
            payOrder.setPayStatus("4");
        }
        if (payOrder.getIsCoupon() == 0) {
            if (payOrder.getIsCoupon() != null && payOrder.getIsCoupon().equals(0)) {
                mallHelloApi.editCouponUser(0, payOrder.getOrderNo());
            }
        }
        return Result.ok("订单已取消");

    }


/**
 * 最新代码
 */
    /**
     * 扫码支付
     *
     * @param payDto
     * @return
     */
    @SneakyThrows
    @PostMapping("/payOrder")
    public Result<?> payOrder(@RequestBody PayDto payDto, HttpServletRequest request) {
        //获取当前ip
        payDto.setSpbillCreateIp(IpUtils.getIpAddr(request));
        if (payDto.getPayPrice() == null || payDto.getTotalPrice() == null || payDto.getCashPay() == null || payDto.getBalancePay() == null || payDto.getActualPrice() == null) {
            return Result.error("传参不正确 金额为null传0");
        }
        //判断金额是否为负数
        if (payDto.getPayPrice().compareTo(BigDecimal.ZERO) < 0 || payDto.getTotalPrice().compareTo(BigDecimal.ZERO) < 0 || payDto.getCashPay().compareTo(BigDecimal.ZERO) < 0 || payDto.getBalancePay().compareTo(BigDecimal.ZERO) < 0 || payDto.getActualPrice().compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("含有金额为负数 请检查金额");
        }
        if (payDto.getOrderType() == 6 || payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
            Boolean aBoolean = payOrderService.checkMerShop(payDto);
            if (aBoolean.equals(Boolean.FALSE)) {
                return Result.error("订单库存数量不匹配！");
            }

        }
        //总金额
        BigDecimal zong = payDto.getCashPay().add(payDto.getBalancePay()).add(payDto.getPayPrice());

        if (payDto.getIsCoupon() != null) {
            if (payDto.getIsCoupon().equals(0)) {
                if (zong.add(payDto.getActivityPrice()).compareTo(payDto.getTotalPrice()) < 0) {
                    return Result.error("金额核算不正确");
                }
            } else {
                if (zong.compareTo(payDto.getTotalPrice()) < 0) {
                    return Result.error("金额核算不正确");
                }
            }
        }
//前端判断后期不一定优惠金额是不是
        if (payDto.getCouponId() == null && payDto.getActivityPrice() != null && (!payDto.getActivityPrice().equals(BigDecimal.ZERO))) {
            payDto.setIsCoupon(1);
        }
        //以上是校验     后期可以 后期可以封装到  一个方法里面
        if (payDto.getOrderType() == 3 && StringUtils.isNotBlank(payDto.getYuYueId())) {
            //查询选择的排期是否人数已满
            SmtYuyueList yuyueList = yuyueListService.getById(payDto.getYuYueId());
            if (yuyueList != null) {
                if (payDto.getCount() > (yuyueList.getCount() - yuyueList.getNum())) {
                    return Result.error(606, "当前排期人数已满，请选择其他排期！");
                }
                if (yuyueList.getStartTime().compareTo(new Date()) > 1) {
                    return Result.error(606, "游戏已经开始无法加入");
                }
            }

        }

        //生成支付订单
        PayOrder payOrder = new PayOrder();
        //生成订单编号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNo = MD5Util.encryptMd5(simpleDateFormat.format(new Date()) + RandomUtil.randomNumbers(10));
        //保存订单
        BeanUtils.copyProperties(payDto, payOrder);
        payOrder.setUserId(payDto.getUid());
        payOrder.setTrkName(getTrkName(payDto));
        payOrder.setOrderType(payDto.getOrderType() == 1 ? 1 : payDto.getOrderType() == 2 ? 2 : payDto.getOrderType() == 3 ? 3 : payDto.getOrderType());
        payOrder.setPayPrice(payDto.getPayPrice());
        payOrder.setOrderNo(orderNo);
        payOrder.setActualPrice(payDto.getActualPrice());
        payOrder.setMerchantId(payDto.getMerId());
        payOrder.setYuyueId(payDto.getYuYueId() == null ? null : payDto.getYuYueId());
        payDto.setOrderCouponNo(payOrder.getOrderNo());
        //根据不同的订单类型创建订单
        Result<?> orderByOrderType = payOrderService.saveOrderByOrderType(payDto, payOrder);
        if (orderByOrderType.getCode() == 200) {
            //添加积分  充值不赠送积分以及成长值
//            if (payDto.getUid() != null && payDto.getOrderType() != 1) {
//                if (payDto.getIntegral() != null) {
//                    YxUser yxUser = new YxUser();
//                    yxUser.setUid(payDto.getUid());
//                    yxUser.setIntegral(payDto.getIntegral());
//                    mallHelloApi.addIntegral(yxUser);
//                }
//                //添加成长值
//                mallHelloApi.growthValueCalculation(payDto);
//            }
            return Result.OK(orderByOrderType.getMessage());
        } else if (orderByOrderType.getCode() == 608) {
            payOrder.setPayStatus("1");
            payOrderService.save(payOrder);
        } else {
            return Result.error(606, orderByOrderType.getMessage());
        }

        //如果是充次订单则走此逻辑
        if (payDto.getOrderType() == 2) {
            payOrderService.card(payDto, payOrder.getId());
        }
        //如果是商家商品订单则走此逻辑
        if (payDto.getOrderType() == 6 || payDto.getOrderType() == 3 && payDto.getShopRecordList() != null) {
            payOrderService.merchantShop(payDto, payOrder.getId());

        }
        //优惠券
        if (payDto.getIsCoupon() != null && payDto.getIsCoupon().equals(0)) {
            mallHelloApi.editCouponUser(payDto.getCouponId(), payDto.getOrderCouponNo());
        }
        Map<String, String> result = null;
        //调用商家微信付款码支付
        //根据商家id查询商家配置的支付信息
        if (payDto.getPayTypes().equals("WeChat")) {
            MerchantPay merchantPay = merchantPayService.getByMerchantId(Integer.valueOf(payDto.getMerId()));
            if (null == merchantPay) return Result.error("未找到其特约子商户，暂不能购买");
            result = payOrderService.servicePayOrder(merchantPay, payDto, payOrder, payOrder.getId());
            if (result.get("result_code") == null || result.get("result_code").equals("FAIL")) {
                return Result.error("支付失败！");
            }
            if (result.get("result_code").equals("SUCCESS") && result.get("return_code").equals("SUCCESS") && result.get("trade_type").equals("MICROPAY")) {
                //更新订单状态
                payOrder.setPayTime(new Date());
                payOrder.setPayStatus("2");
                payOrder.setTransactionId(result.get("transaction_id"));
                payOrder.setPayType("WeChat");
                payOrderService.updateById(payOrder);

                //用户余额处理
                Result<?> balance = payOrderService.balance(payDto);
                if (balance.getCode() != 200) {
                    return Result.error(606, balance.getMessage());
                }
                //添加积分
//            if (payDto.getUid() != null) {
//                if (payDto.getIntegral() != null) {
//                    YxUser yxUser = new YxUser();
//                    yxUser.setUid(payDto.getUid());
//                    yxUser.setIntegral(payDto.getIntegral());
//                    mallHelloApi.addIntegral(yxUser);
//                }
//                //添加成长值
//                mallHelloApi.growthValueCalculation(payDto);
//            }
                return Result.OK("支付成功！");
            }

            //支付返回需要输入支付密码时走此逻辑
            if (result.get("err_code").equals("USERPAYING")) {
                Thread.sleep(20000);
                Result<?> orderStatus = null;
                //请求查询订单接口
                orderStatus = payOrderService.queryOrder(payDto, payOrder.getId());
                if (orderStatus.getCode() != 200) {
                    return Result.error(606, orderStatus.getMessage());
                }

                //添加积分
//            if (payDto.getUid() != null) {
//                if (payDto.getIntegral() != null) {
//                    YxUser yxUser = new YxUser();
//                    yxUser.setUid(payDto.getUid());
//                    yxUser.setIntegral(payDto.getIntegral());
//                    mallHelloApi.addIntegral(yxUser);
//                }
//                //添加成长值
//                mallHelloApi.growthValueCalculation(payDto);
//            }
                return Result.OK("支付成功");
            }
        }
        if (payDto.getPayTypes().equals("Alipay")) {
            return payOrderService.serviceAlipayOrder(payDto, payOrder, payOrder.getId());
        }
        return Result.error(606, result.get("err_code_des"));
    }

    //     1 储值 2 次卡 3 商品 4 抖音 5美团 6 商家普通商品 7 扣次订单
    private String getTrkName(PayDto payDto) {
        Integer orderType = payDto.getOrderType();
        switch (orderType) {
            case 1:
                return "用户储值";
            case 2:
                return "次卡充值";
            case 3:
                return StringUtils.isNotBlank(payDto.getTrkName()) ? payDto.getTrkName() : "悦动商品";
            case 4:
                return "抖音消费";
            case 5:
                return "美团消费";
            case 6:
                if (!payDto.getShopRecordList().isEmpty())
                    return payDto.getShopRecordList().stream().map(SmtMerchantShopRecord::getShopName).collect(Collectors.joining(","));
                return "--普通商品";
            case 7:
                return "扣次订单";
        }
        return "未定义的商品";
    }


    /**
     * 申请退款
     *
     * @param refundDto
     * @return
     */
    @SneakyThrows
    @PostMapping("/refund")
    public Result<?> refund(@RequestBody RefundDto refundDto) {

        //判断当前订单是否已经退款
        QueryWrapper<RefundRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", refundDto.getOutTradeNo());
        RefundRecord record = recordService.getOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(record) && record.getRefundStatus() == 2) {
            return Result.error(606, "当前订单已退款!");
        }

        RefundRecord refundRecord = new RefundRecord();
        PayOrder payOrder = payOrderService.getById(refundDto.getOutTradeNo());
        if (payOrder == null) {
            return Result.error(606, "订单不存在");
        }
        if (payOrder.getOrderType().equals(4) || payOrder.getOrderType().equals(5)) {
            return Result.error("当前订单属于美团或者抖音核销，不可退款或者踢出！");
        }
        if (!payOrder.getPayStatus().equals("2") || payOrder.getSplitType().equals(1)) {
            return Result.error(606, "当前订单状态未支付完成、已经退款、已经分账！");
        }
        //判断排期是否过期过期后不进行退款
        if (payOrder.getOrderType() == 3) {
            LambdaQueryWrapper<SmtYuyueUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SmtYuyueUser::getLinkPayOrderNo, payOrder.getOrderNo());
            List<SmtYuyueUser> smtYuyueUsers = smtYuyueUserService.list(wrapper);
            if (!CollectionUtils.isEmpty(smtYuyueUsers)) {
                SmtYuyueList yuyueListById = yuyueListService.getById(smtYuyueUsers.get(0).getId());
                if (yuyueListById != null) {
                    if (yuyueListById.getStartTime().compareTo(new Date()) < 0) {
                        return Result.error(606, "订单已经过期，不可退款");
                    }
                }
            }

        }
        Result<?> refundByOrderType = recordService.refundByOrderType(refundDto, payOrder, refundRecord);
        if (refundByOrderType.getCode() == 200) {
            //退还积分
//            if (payOrder.getUserId() != null) {
//                if (payOrder.getIntegral() != null) {
//                    YxUser yxUser = new YxUser();
//                    yxUser.setUid(payOrder.getUserId());
//                    yxUser.setIntegral(payOrder.getIntegral());
//                    mallHelloApi.subIntegral(yxUser);
//                }
//                //扣除成长值
//                mallHelloApi.subgrowthValues(payOrder.getUserId(), payOrder.getOrderNo());
//            }
            return Result.OK(refundByOrderType.getMessage());
        } else if (refundByOrderType.getCode() == 608) {
            if (payOrder.getOrderType() == 1) {
                BigDecimal bigDecimal = smtStoredUserPointService.subPoint(payOrder.getTotalPrice(), payOrder.getGivePrice(), payOrder.getUserId(), String.valueOf(refundDto.getMerId()), payOrder.getOrderNo());
                if (bigDecimal == null) {
                    return Result.error(606, "用户卡点状态不支持退款");
                }
                refundDto.setRefundPrice(bigDecimal);
            }
            //调用微信支付退款
            if (payOrder.getPayType().contains("WeChat")){
                Map<String, String> stringStringMap = recordService.refund(refundDto, refundDto.getOutTradeNo());
                if (stringStringMap.get("return_code").equals("SUCCESS") && stringStringMap.get("result_code").equals("SUCCESS")) {
                    //生成退款记录
                    BeanUtils.copyProperties(refundDto, refundRecord);
                    refundRecord.setTotalFee(refundDto.getTotalPrice());
                    refundRecord.setRefundFee(refundDto.getRefundPrice());
                    refundRecord.setRefundId(stringStringMap.get("refund_id"));
                    refundRecord.setMchId(stringStringMap.get("mch_id"));
                    refundRecord.setSubMchId(stringStringMap.get("sub_mch_id"));
                    refundRecord.setRefundStatus(2);
                    recordService.save(refundRecord);

                    //处理订单逻辑
                    Result<?> result = payOrderService.updateOrder(refundRecord);
                    if (result.getCode() != 200) {
                        return Result.error(606, result.getMessage());
                    }
                    //退还积分
//                if (payOrder.getUserId() != null) {
//                    if (payOrder.getIntegral() != null) {
//                        YxUser yxUser = new YxUser();
//                        yxUser.setUid(payOrder.getUserId());
//                        yxUser.setIntegral(payOrder.getIntegral());
//                        mallHelloApi.subIntegral(yxUser);
//                    }
//                    //扣除成长值
//                    mallHelloApi.subgrowthValues(payOrder.getUserId(), payOrder.getOrderNo());
//                }
                    return Result.OK("退款成功！");
                }else {
                    return Result.error(606, stringStringMap.get("err_code_des"));
                }

            }

            if (payOrder.getPayType().contains("Alipay")){
               return recordService.refundZfb(refundDto,refundDto.getOutTradeNo(), refundRecord);
            }

//
            return Result.error(606,"退款失败！");
        } else {
            return Result.error(606, refundByOrderType.getMessage());
        }
    }

    @GetMapping("/zhifub")
    public Result zhifub(@RequestParam String code, @RequestParam String orderNo) throws AlipayApiException {
        String privateKey = ZfbConfig.PRIVATE_KEY;
        String alipayPublicKey = ZfbConfig.ALIPAY_PUBLIC_KEY;
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(ZfbConfig.APP_ID);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        request.putOtherTextParam("app_auth_token", "202203BB24ccff59ec174b0398dbffdf30b4bX32");
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setOutTradeNo(orderNo);
        model.setTotalAmount("0.01");
        model.setSubject("Iphone6 16G");
        model.setAuthCode(code);
        model.setScene("bar_code");
        model.setSellerId("2088802797880320");
        request.setBizModel(model);
        AlipayTradePayResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println(response);
            return Result.ok(response);
        }
        System.out.println("receiptAmount" + response.getReceiptAmount());
        System.out.println("tradeNo" + response.getTradeNo());
        System.out.println("totalAmount" + response.getTotalAmount());
        return Result.error("失败", response);
//        return Result.error("失败",response.getSubMsg());
    }


    @GetMapping("/cjaxuinZfb")
    public Result cjaxuinZfb(@RequestParam String orderNo) throws AlipayApiException {
        String privateKey = ZfbConfig.PRIVATE_KEY;
        String alipayPublicKey = ZfbConfig.ALIPAY_PUBLIC_KEY;
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(ZfbConfig.APP_ID);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.putOtherTextParam("app_auth_token", "202203BB24ccff59ec174b0398dbffdf30b4bX32");
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
//        model.setOutTradeNo(orderNo);
        model.setTradeNo(orderNo);
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("tradeStatus---------" + response.getTradeStatus());//TRADE_SUCCESS
            return Result.ok(response);
        }
        return Result.error("失败", response);
    }


    @GetMapping("/zhifubTk")
    public Result zhifubTk(@RequestParam String code, @RequestParam String orderNo) throws AlipayApiException {
        String privateKey = ZfbConfig.PRIVATE_KEY;
        String alipayPublicKey = ZfbConfig.ALIPAY_PUBLIC_KEY;
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(ZfbConfig.APP_ID);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.putOtherTextParam("app_auth_token", "202203BB24ccff59ec174b0398dbffdf30b4bX32");
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setRefundAmount("0.01");
        model.setOutTradeNo("88888889999");
        model.setOutRequestNo("66656548982255");
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return Result.ok(response);
        }
        return Result.error("失败", response);
    }


    @GetMapping("/tkCx")
    public Result tkCx(@RequestParam String orderNo) throws AlipayApiException {
        String privateKey = ZfbConfig.PRIVATE_KEY;
        String alipayPublicKey = ZfbConfig.ALIPAY_PUBLIC_KEY;
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(ZfbConfig.APP_ID);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        request.putOtherTextParam("app_auth_token", "202203BB24ccff59ec174b0398dbffdf30b4bX32");
        AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
        model.setOutRequestNo("66656548982255");
        model.setOutTradeNo("88888889999");
        request.setBizModel(model);
        AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("RefundStatus" + response.getRefundStatus());
            return Result.ok(response);
        }
        return Result.error("失败", response);
    }

}
